package com.dana.friend.manager;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.core.constants.CacheConstant;
import com.core.enums.ResultCode;
import com.dana.friend.domain.question.Question;
import com.dana.friend.mapper.question.QuestionMapper;
import com.dana.redis.service.RedisService;
import com.dana.security.exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;


@Component
public class QuestionCacheManager {
    @Autowired
    private RedisService redisService;
    @Autowired
    private QuestionMapper questionMapper;
    //看是否有数据
    public Long getListSize() {
        //返回缓存中是否有数据
        return redisService.getListSize(CacheConstant.QUESTION_LIST);
    }

    //刷新缓存
    public void refreshCache() {
        List<Question> questionList = questionMapper.selectList(new LambdaQueryWrapper<Question>()
                .select(Question::getQuestionId)
                .orderByDesc(Question::getCreateTime));
        if (questionList==null){
            return;
        }
        //转换为id
        List<Long> questionIdList = questionList
                .stream()
                .map(Question::getQuestionId)
                .toList();
        redisService.rightPushAll(CacheConstant.QUESTION_LIST,questionIdList);
    }

    /**
     * 前一题
     * 通过questionId定位到本道题,判断不是第一题之后返回前一题id
     * @param questionId
     * @return
     */
    public Long preQuestion(Long questionId) {
        Long index = redisService.indexOf(CacheConstant.QUESTION_LIST, questionId);
        if (index==0){
            throw new ServiceException(ResultCode.FAILED_FIRST_QUESTION);
        }
        return redisService.index(CacheConstant.QUESTION_LIST, index - 1, Long.class);
    }

    /**
     * 下一题
     * @param questionId
     * 通过questionId定位到本道题,判断不是最后一题之后返回后一题id
     * @return
     */
    public Object nextQuestion(Long questionId) {
        Long index = redisService.indexOf(CacheConstant.QUESTION_LIST, questionId);
        Long lastIndex = getListSize() - 1;
        if (index == lastIndex) {
            throw new ServiceException(ResultCode.FAILED_LAST_QUESTION);
        }
        return redisService.index(CacheConstant.QUESTION_LIST, index + 1, Long.class);
    }
}
